﻿using System;
using Microsoft.Extensions.Caching.Memory;

namespace WPay.Infrastructure.Unity
{
    public class RayPIMemoryCache
    {
        // public static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

        static Redis _cache = new Redis();

        /// <summary>
        /// 验证缓存项是否存在
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public static bool Exists(string key)
        {

            return _cache.KeyExists(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            return _cache.StringGet<T>(key);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiresSliding">滑动过期时长（如果在过期时间内有操作，则以当前时间点延长过期时间）</param>
        /// <param name="expiressAbsoulte">绝对过期时长</param>
        /// <returns></returns>
        public static bool AddMemoryCache<T>(string key, T value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
        {
            if (Exists(key))
            {
                _cache.KeyDelete(key);
            }
            _cache.StringSet<T>(key, value, expiressAbsoulte);
            return Exists(key);
        }
    }
}